<template>
    <div>
        <h1>{{tableName}}
            <el-button @click="()=>saveTableView()" type="text">保存视图</el-button>
            <el-button @click="()=>zipExport()" type="text">一键导出</el-button>
        </h1>
        <div style="display: flex;">
            <!--            查询-->
            <div style="padding-bottom: 10px;padding-right: 10px;">
                <ul>
                    <li v-for="field in fields" v-if="!field.hidden">
                        <span>{{field.字段名称}}</span>
                        <span style="padding:0px 10px;">like</span>
                        <input type="text" placeholder="查询" v-model="filterOption[field.字段名称]"/>
                    </li>
                </ul>

                <el-button type="primary" @click="()=>ajaxList()">查询</el-button>
                <div>
                    <span>{{loading?'加载中':error}}</span>
                </div>
            </div>
            <!-- 数据 -->
            <div>
                <!--隐藏字段-->
                <div>
                    hidden field:
                    <ul style="display: flex;flex-wrap: wrap;list-style: none;">
                        <li v-for="field in fields"
                            style="padding: 10px;background: #dddddd;cursor: pointer"
                            @click="()=>{field.hidden=!field.hidden;$forceUpdate()}"
                            :style="`${field.hidden?'background: #ddd;border:1px solid #ddd;':'background: #fff;border:1px solid #ddd;'}`"
                        >
                            {{ field.字段名称 }}({{ field.字段说明 }})
                        </li>
                    </ul>
                </div>
                <!--  查询              -->
                <div style="padding: 20px 0;">
                    <div> 手动输入sql:</div>
                    <input type="text" placeholder="key=value /  key like %value% /  key >111 " v-model="whereSql2"
                           style="width: 100%;"/>
                </div>
                <div>
                    <el-button type="text" @click="()=>triggerAddDialog({})">添加</el-button>
                </div>

                <table style="width: 100%;table-border-color-light: #ddd;" border="1">
                    <thead>
                    <tr>
                        <!--                        点击头部可以字段的具体描述-->
                        <td
                                @click="()=>showDescFiled(field)"
                                v-for="field in fields" style="font-weight: 600;" v-if="!field.hidden">{{field['字段名称']}}
                        </td>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="row in tableList">
                        <td v-for="field in fields" style="padding: 10px;" v-if="!field.hidden">
                            <div v-html="renderFiled(row[field['字段名称']],field,row)"></div>
                        </td>
                        <td>
                            <el-button type="text" @click="()=>createCsv(row)">生成controller,service,view</el-button>
                            <el-button type="text" @click="()=>json(row)">复制成json</el-button>
                            <el-button type="text" @click="()=>restAddUpdate(row)">生成restAddUpdate</el-button>
                            <el-button type="text" @click="()=>restListPage(row)">生成restListPage</el-button>
                            <el-button type="text" @click="()=>navicat(row)">navicat</el-button>
                            <el-button type="text" @click="()=>createLeftJoinSql(row)">left join</el-button>
         <!--                   <el-button type="text" @click="()=>addPostMan(row)">add postman</el-button>
                            <el-button type="text" @click="()=>updatePostMan(row)">update postman</el-button>
                            <el-button type="text" @click="()=>postmanGetList(row)">get/list postman</el-button>
                            <el-button type="text" @click="()=>triggerUpdateDialog(row)">修改</el-button>
                            <el-button type="text" @click="()=>triggerAddDialog(row)">添加</el-button>-->
                        </td>
                    </tr>
                    </tbody>


                </table>

                <el-pagination
                        layout="prev, pager, next"
                        :page-size="pageSize"
                        :current-page="pageNum"
                        :total="total"
                        @size-change="(pageSize) => sizeChange(pageSize)"
                        @current-change="(pageNum) => currentChange(pageNum)"
                >
                </el-pagination>
            </div>

        </div>

        <div>
            <h2>desc
                <el-button @click="()=>createLeftJoinSql()">生成leftJoinSql</el-button>
            </h2>
            <ul>
                <li v-for="field in fields">
                    字段名称: {{ field.字段名称 }} <br/>
                    字段类型长度: {{ field.字段类型长度 }}<br/>
                    字段说明: {{ field.字段说明 }}<br/>
                    <div v-if="bindFieldsMap[field.字段名称]" style="color: #42b983">
                        逻辑外键:
                        <!-- {{ bindFieldsMap[field.字段名称] }} -->
                        {{ bindFieldsMap[field.字段名称].subTable }}.
                        {{ bindFieldsMap[field.字段名称].subfieldName }}
                    </div>
                    <br/>
                </li>
                <div></div>
                <!-- ul>
                  <li v-for="item in bindFields">{{ item }}</li>
                </ul> -->
            </ul>
        </div>
        <input type class="hide" id="input_copy_txt_to_board" value="" hidden/>

        <modifyDialog ref="modifyDialog"></modifyDialog>
    </div>
</template>
<script>
    import {
        copy2bang,
        createA,
        firstworldupp,
        getCookie,
        getUrlParamNative,
        safeParseJson,
        toHump
    } from "../../utils/utils";
    import lodash from 'lodash'

    export default {
        data() {
            return {
                loading: false,
                error: '',
                filterOption: {},
                desc: {},
                tableList: [],
                pageNum: 0,
                pageSize: 10,
                total: 0,
                tableName: "",
                fields: [],
                bindFields: [],
                bindFieldsMap: {},
                bindFields2: [],
                //手动输入sql
                whereSql2: "",
            };
        },
        components: {
            modifyDialog: () => import('./modifyDailog.vue')
        },
        async mounted() {
            this.tableName = getUrlParamNative("table");
            if (this.tableName) {
                var a = safeParseJson(sessionStorage.getItem(`${this.tableName}View`))
                if (a) {
                    this.$data.fields = a && a.fields
                    this.$data.filterOption = a && a.filterOption || {};
                    this.$data.whereSql2 = a && a.whereSql2 || '';
                }
            }
            if (this.$data.fields && this.$data.fields.length == 0) {
                await this.ajaxFields();
            }

            this.ajaxList();
            document.title = this.tableName
            this.ajaxBindFields()
        },
        methods: {
            zipExport(){
                createA(`/api/databases/exportZip?tableName=${this.$data.tableName}`)
            },
            triggerUpdateDialog(row) {
                this.$refs['modifyDialog'].init(row, true)
            },
            triggerAddDialog(row) {
                this.$refs['modifyDialog'].init(row, false)
            },
            addPostMan(row) {
                delete row.pageNum
                delete row.pageSize
                var token = getCookie("token");
                delete row.id;
                var _row = {}
                lodash.map(row, (value, key) => {
                    if (key != 'create_time' && key != 'update_time') {
                        if (value) {
                            if (typeof (value) == 'object') {
                                value = value.value
                            }
                        }
                        var value = value ? value : ''
                        if (value == 'null') {
                            value = ""
                        }
                        //get请求参数太长 报错
                        if (value && value.length >= 40) {
                            value = value.substring(0, 40)
                        }
                        _row[key] = value
                    }
                })

                var resultStr = `curl "http://localhost:8080/mock/${toHump(this.tableName)}/add"
                   --header "token: ${token}"
                    -H "Content-Type: application/json"
                    -X POST
                    -d '${JSON.stringify(_row)}'
                `
                console.log("resultStr", resultStr)
                window._vm.$notify({
                    title: "postman list get  ",
                    dangerouslyUseHTMLString: true,
                    message: `<div style="padding-right: 10px;width: 300px;white-space:pre-wrap;word-break:break-all"> ${resultStr}</div>`
                });
                copy2bang(resultStr)
            },
            updatePostMan(row) {
                delete row.pageNum
                delete row.pageSize
                var token = getCookie("token");
                delete row.id;
                var _row = {}
                lodash.map(row, (value, key) => {
                    if (key != 'create_time' && key != 'update_time') {
                        if (value) {
                            if (typeof (value) == 'object') {
                                value = value.value
                            }
                        }
                        var value = value ? value : ''
                        if (value == 'null') {
                            value = ""
                        }
                        //get请求参数太长 报错
                        if (value && value.length >= 40) {
                            value = value.substring(0, 40)
                        }
                        _row[key] = value
                    }
                })

                var resultStr = `curl "http://localhost:8080/mock/${toHump(this.tableName)}/update?id=${row.id}"
                   --header "token: ${token}"
                    -H "Content-Type: application/json"
                    -X POST
                    -d '${JSON.stringify(_row)}'
                `
                console.log("resultStr", resultStr)
                window._vm.$notify({
                    title: "postman list get  ",
                    dangerouslyUseHTMLString: true,
                    message: `<div style="padding-right: 10px;width: 300px;white-space:pre-wrap;word-break:break-all"> ${resultStr}</div>`
                });
                copy2bang(resultStr)
            },
            postmanGetList(row) {
                row.pageNum = 0;
                row.pageSize = 10;
                var token = getCookie("token");
                var strParams = ""
                lodash.map(row, (value, key) => {
                    if (key != 'create_time' && key != 'update_time') {
                        if (value) {
                            if (typeof (value) == 'object') {
                                value = value.value
                            }
                        }
                        var value = value ? value : ''
                        if (value == 'null') {
                            value = ""
                        }
                        //get请求参数太长 报错
                        if (value && value.length >= 40) {
                            value = value.substring(0, 40)
                        }
                        strParams += `${key}=${value}&`
                    }
                })
                strParams = strParams.substring(0, strParams.length - 1)
                var resultStr = `curl "http://localhost:8080/mock/${toHump(this.tableName)}/page?${strParams}"
                   --header "token: ${token}"
                `
                console.log("resultStr", resultStr)
                window._vm.$notify({
                    title: "postman list get  ",
                    dangerouslyUseHTMLString: true,
                    message: `<div style="padding-right: 10px;width: 300px;white-space:pre-wrap;word-break:break-all"> ${resultStr}</div>`
                });
                copy2bang(resultStr)
            },
            ajaxBindFields() {
                axios
                    .post(`/databases/getBindFields`, {masterTable: this.tableName}).then(res => res.data).then(res => {
                    this.bindFields2 = res
                })

            },
            ajaxFields() {
                var self = this;
                axios
                    .post(`/databases/getTableFields`, {tableName: this.tableName})
                    .then((res) => res.data)
                    .then((res) => {
                        //处理隐藏字段还是显示字段  一般id显示 name显示 其他的直接隐藏
                        res.fields = res.fields.map(item => {
                            var hidden = item.字段名称.toLowerCase().indexOf('id') >= 0 || item.字段名称.toLowerCase().indexOf('name') >= 0 || item.字段名称.toLowerCase().indexOf('status') >= 0
                            item.hidden = !hidden
                            return item
                        })
                        self.fields = res.fields;
                        self.bindFields = res.bindFields;
                        for (const index in self.bindFields) {
                            self.bindFieldsMap[self.bindFields[index].masterfieldName] =
                                self.bindFields[index];
                        }
                    });
            },
            createWhereSql() {
                var filterOption = this.filterOption
                var sql = ``
                lodash.map(filterOption, (value, key) => {
                    if (value) {
                        var isNumber = typeof (value) == 'number'
                        if (isNumber) {
                            value = value
                        } else {
                            value = `'%${value}%'`
                        }
                        sql += `${key} like ${value} and `
                    }
                })
                //去掉最后面的三个字（and）
                if (sql) {
                    sql = sql.substring(0, sql.length - 4)
                    sql = 'where ' + sql
                }
                return sql;
            },

            ajaxList() {
                this.loading = true;
                //点击查询的时候字段保存视图
                sessionStorage.setItem(`${this.tableName}View`, JSON.stringify({
                    fields: this.$data.fields,
                    filterOption: this.$data.filterOption,
                    whereSql2: this.$data.whereSql2
                }))

                console.log('点击查询的时候自动保存视图')

                var self = this;
                //构造查询条件 whereSql
                var whereSql = this.createWhereSql()
                //补充手动条件
                var connectStr = " "
                if (!whereSql && this.whereSql2) {
                    connectStr = ' where '
                }
                if (whereSql && this.whereSql2) {
                    connectStr = ' and '
                }
                var resultSql = whereSql + connectStr + this.whereSql2
                axios.post(`/databases/getTableData`, {
                    tableName: this.tableName,
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    whereSql: resultSql,
                })
                    .then((res) => res.data)
                    .then((res) => {
                        this.loading = false;
                        this.error = ""
                        this.tableList = res.result;
                        this.total = Number(res.total);

                        //添加 jquery事件
                        self.$nextTick(() => {
                            setTimeout(() => {
                                $('.subFiledSpan').click(async (e) => {

                                    // $(e.currentTarget).siblings('.showZoom').html(e.currentTarget.dataset.desc)
                                    //裁断 value 只需要前面10个
                                    var subValue = e.currentTarget.dataset.value
                                    var subfieldvalue = safeParseJson(e.currentTarget.dataset.subfieldvalue)
                                    var descJson = await axios.post(`/databases/ajaxLeftJoin`, {
                                        subfieldvalue: subfieldvalue,
                                        subValue: subValue
                                    }).then(res => res.data)
                                    var newDescJoson = {}
                                    lodash.map(descJson, (value, key) => {
                                        if (typeof (value) == 'object') {
                                            newDescJoson[key] = value

                                        } else {
                                            newDescJoson[key] = value && (value + "").substring(0, 10)
                                        }
                                    })
                                    window.closeNotifyIndex && window.closeNotifyIndex.close();
                                    window.closeNotifyIndex = window._vm.$notify({
                                        title: e.currentTarget.dataset.title,
                                        dangerouslyUseHTMLString: true,
                                        message: `<pre>${JSON.stringify(newDescJoson, null, 2)}</pre>`
                                    });
                                })
                            }, 500)
                        })


                    }).catch(e => {
                    this.loading = ""
                    this.error = e.response && e.response.data && e.response.data.message
                });


            },
            currentChange(pageNum) {
                this.pageNum = pageNum;
                this.tableList = [];
                this.ajaxList();
            },
            sizeChange(pageSize) {
                this.pageSize = pageSize;
                this.tableList = [];
                this.ajaxList();
            },
            renderFiled(value, field, row) {
                if (value && value.subFieldValue) {
                    return value.value + `<div>
      <span style='padding-top: 5px;cursor: pointer' class='subFiledSpan'
      data-value='${value.value}'
      data-subfieldvalue='${JSON.stringify(value.subFieldValue)}'>查看</span>
      <div class="showZoom"></div>
</div>

                       `
                } else {
                    return value
                }
            },
            showDescFiled(field) {
                if (window.showDescFiledIntance) {
                    window.showDescFiledIntance.close()
                }
                window.showDescFiledIntance = this.$notify({
                    title: field.字段名称,
                    dangerouslyUseHTMLString: true,
                    message: `<pre>${JSON.stringify(field, null, 2)}</pre>`
                });
            },
            //保存整个$data  key=`${tableName}View`
            saveTableView() {
                sessionStorage.setItem(`${this.tableName}View`, JSON.stringify({
                    fields: this.$data.fields,
                    filterOption: this.$data.filterOption
                }))

                this.$message('保存成功')
            },
            json(row) {
                window.navicat$notify && window.navicat$notify.close();
                window.navicat$notify = window._vm.$notify({
                    title: '【json】 复制成功',
                    dangerouslyUseHTMLString: true,
                    message: `<pre>${JSON.stringify(row, null, 2)}</pre>`
                });
                this.copyText(JSON.stringify(row))
            },

            navicat(row) {
                var str = ``
                var filterOption = row
                var sql = ``
                lodash.map(filterOption, (value, key) => {
                    //有一些key 完全不需要作为查询条件
                    if (key == 'create_time' || key == 'update_time' || key == 'version') {
                        return false
                    }
                    if (value) {
                        if (value.value) {
                            value = value.value
                        }
                        var isNumber = typeof (value) == 'number'
                        if (isNumber) {
                            value = value
                        } else {
                            value = `'%${value}%'`
                        }
                        sql += `${key} like ${value} and `
                    }
                })
                //去掉最后面的三个字（and）
                if (sql) {
                    sql = sql.substring(0, sql.length - 4)
                    sql = 'where ' + sql
                }


                var sql = ` select * from ${this.tableName} ${sql} `
                console.log("row", row, sql)
                window.navicat$notify && window.navicat$notify.close();
                window.navicat$notify = window._vm.$notify({
                    title: '【navicat 查询】 复制成功',
                    dangerouslyUseHTMLString: true,
                    message: `${sql}`
                });
                this.copyText(sql)
            },
            copyText(str) {
                var txt = str.trim();
                $("#input_copy_txt_to_board").val(txt);//赋值
                $("#input_copy_txt_to_board").removeClass("hide");//显示
                $("#input_copy_txt_to_board").focus();//取得焦点
                $("#input_copy_txt_to_board").select();//选择
                copy2bang(txt);
                $("#input_copy_txt_to_board").addClass("hide");//隐藏
            },
            restAddUpdate(row) {
                var sql = `
                //${this.tableName} 添加或者修改  <br/>
                var params=${JSON.stringify(row)};
                axios.post('/${this.tableName}/add',params).then(res=>res.data).then(res=>{
                    console.log(res)
                })
                `
                console.log(sql)
                this.copyText(sql)
                window.navicat$notify && window.navicat$notify.close();
                window.navicat$notify = window._vm.$notify({
                    title: 'add/update api 复制成功',
                    dangerouslyUseHTMLString: true,
                    message: `${sql}`
                });
            },
            restListPage(row) {
                var _row = {}
                lodash.map(row, (item, key) => {
                    if (item && item.value) {
                        _row[key] = item.value
                    } else {
                        _row[key] = item
                    }
                })
                var sql = `
                //${this.tableName} 分页或者查询列表 <br/>
                var params=${JSON.stringify({..._row, pageNum: 0, pageSize: 1})};
                axios.get('/${this.tableName}/page',{params:params}).then(res=>res.data).then(res=>{
                    console.log(res)
                })
                `
                console.log(sql)
                this.copyText(sql)
                window.navicat$notify && window.navicat$notify.close();
                window.navicat$notify = window._vm.$notify({
                    title: 'list/page api 复制成功',
                    dangerouslyUseHTMLString: true,
                    message: `${sql}`
                });
            },
            createWhereSql2(row) {
                var self = this;
                if (!row) {
                    row = this.tableList[0]
                }
                var sql = ``
                lodash.map(row, (value, key) => {

                    //有些字段完全没必要做查询
                    if (key == 'create_time' && key == 'update_time') {
                        return false
                    }
                    if (value) {
                        if (value.value) {
                            value = value.value
                        }
                        var isNumber = typeof (value) == 'number'
                        if (isNumber) {
                            value = value
                        } else {
                            value = `'%${value}%'`
                        }
                        sql += `${self.tableName}.${key} like ${value} and `
                    }
                })

                //去掉最后面的三个字（and）
                if (sql) {
                    sql = sql.substring(0, sql.length - 4)
                    sql = 'where ' + sql
                }
                return sql;
            },
            createLeftJoinSql(row) {
                //select * from where table t1 left join table t2 on t2.id=t1.xx_id
                var str_xinxing = ``
                this.fields.map(item => {
                    if (!item.hidden) {
                        //主表的字段
                        str_xinxing += `${this.tableName}.${item.字段名称},`
                    }
                })

                //加入其他表的字段
                for (let i = 0; i < this.bindFields2.length; i++) {
                    var bind = this.bindFields2[i]

                    for (let j = 0; j < bind.fields.length; j++) {
                        var field = bind.fields[j]
                        /*name*/
                        str_xinxing += `${bind.subTable}.${field.name} as ${toHump(bind.subTable)}${firstworldupp(toHump(field.name))},`
                    }
                }
                str_xinxing = str_xinxing.substring(0, str_xinxing.length - 1)

                /*
                * masterTable: "sys_user_role"
    masterfieldName: "user_id"
    subTable: "sys_user"
    subfieldName: "user_id"
                * */
                var leftJionStr = ''
                for (let i = 0; i < this.bindFields2.length; i++) {
                    var bind = this.bindFields2[i]
                    leftJionStr += `left  join  ${bind.subTable} on ${bind.masterTable}.${bind.masterfieldName}=${bind.subTable}.${bind.subfieldName} \n`
                }

                var sql = `
                select ${str_xinxing} from ${this.tableName} as ${this.tableName}  \n
                ${leftJionStr} \n
                ${this.createWhereSql2(row)}`
                console.log("left jopin ", sql)
                this.copyText(sql)
                window.navicat$notify && window.navicat$notify.close();
                window.navicat$notify = window._vm.$notify({
                    title: 'left join 复制成功',
                    dangerouslyUseHTMLString: true,
                    message: `${sql}`
                });
            },
            createCsv(row) {
                createA(`/createCvs?table=${this.tableName}`, '_blank')
            },

        }
        ,
    }
    ;
</script>
